import * as qiniu from 'qiniu-js'
import Vue from 'vue'
let vue = new Vue()
const CONFIG = {
  useCdnDomain: true, // 使用cdn加速
  region: qiniu.region.z0 // 华东地区
}
export default {
  // 上传文件
  createQiniuUploader ({ file, putExtra, nextCb, errorCb, completeCb }) {
    this.initBaseConf(baseConf => {
      let _putExtra = putExtra || {
        fname: '',
        params: { 'x:tenantId': baseConf.tenantId },
        mimeType: null
      }
      let key = this.getKey(file)
      const observable = qiniu.upload(file, key, baseConf.uptoken, _putExtra, CONFIG)
      observable.subscribe({
        next: res => {
          if (nextCb && typeof nextCb === 'function') {
            nextCb(res) // 主要用来展示进度
          }
        },
        error: err => {
          if (errorCb && typeof errorCb === 'function') {
            errorCb(err)
          }
          if (err.code === 614) {
            vue.$notify.error({
              title: '错误',
              message: '文件已存在，请更换文件名再试'
            })
          } else {
            vue.$notify.error({
              title: '错误',
              message: '上传失败'
            })
          }
        },
        complete: res => {
          if (completeCb && typeof completeCb === 'function') {
            completeCb(res, baseConf)
          }
        }
      })
    })
  },
  // 获取上传凭证和图片存储空间读取域名
  getUptoken () {
    return new Promise((resolve, reject) => {
      let url = `/oss/getAuth?tenantId=${localStorage.getItem('tenantId')}`
      vue.$get(url).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 获取上传域名  http://upload.qiniup.com
  getUploadUrl () {
    return new Promise((resolve, reject) => {
      qiniu.getUploadUrl(CONFIG).then(url => {
        resolve(url)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 初始化七牛云存储的配置
  initBaseConf (cb) {
    let baseConfig = {}
    this.getUptoken()
      .then(res => {
        baseConfig.uptoken = res.data.uptoken
        baseConfig.domain = res.data.domain
        baseConfig.tenantId = res.data.tenantId
        return this.getUploadUrl()
      })
      .then(url => {
        baseConfig.url = url
        cb(baseConfig)
      })
      .catch(err => {
        vue.handleError(err)
      })
  },
  // 定义上传文件名
  getKey (file) {
    let header = sessionStorage.getItem('domain_header_tag')
    // 当save_key和unique_names设为false时，该方法将被调用
    let timeStamp = this.getTimeStamp()
    let type = '.' + ((file.type && file.type.split('/')[1]) || 'png')
    var key = (header ? (header + '_') : '') + timeStamp + type
    return key
  },
  // 获取时间戳
  getTimeStamp () {
    let now = new Date()
    let Y = now.getFullYear()
    let M = '0' + (now.getMonth() + 1)
    let D = '0' + now.getDate()
    let h = '0' + now.getHours()
    let m = '0' + now.getMinutes()
    let s = '0' + now.getSeconds()
    let ms = '000' + now.getMilliseconds()
    return Y + M.substr(-2) + D.substr(-2) + h.substr(-2) + m.substr(-2) + s.substr(-2) + ms.substr(-4)
  }
}
